package example.simple_mindmap.common.designs.chain;

import org.springframework.context.ApplicationContext;

/**
 * @Program: 8.mindmap
 * @Author: 海里的鱼
 * @Create: 2024-09-10 10:30
 * @Name: 链路处理者
 * @Desc: TODO
 */
public class ChainHandler {
    //Bean容器
    private ApplicationContext beanContext;
    //链路列表
    private ChainList chainList;
    //数据
    private ChainData<?> data;

    /** ---------------------------------------------------------------------------------------------------------------------
     * @Method  : 启动链路
     * @Describe: TODO
     **/
     public boolean start(){
         //判断链路是否为空
         if(chainList == null){
             return false;
         }

         //遍历执行链路
        for(ChainNode chainNode : chainList.getChainNodes()){
            IChainHandlerStrategy handler = getHandler(chainNode);
            if(handler == null){
                return false;
            }
            if(!handler.process(data)){
                return false;
            }
        }
        return true;
    }

    public boolean start(ChainList chainList){
        //判断链路是否为空
        if(chainList == null){
            return false;
        }else {
            this.chainList = chainList;
        }

        //遍历执行链路
        for(ChainNode chainNode : chainList.getChainNodes()){
            IChainHandlerStrategy handler = getHandler(chainNode);
            if(handler == null){
                return false;
            }
            if(!handler.process(data)){
                return false;
            }
        }
        return true;
    }

    private IChainHandlerStrategy getHandler(ChainNode chainNode){
        if( chainNode.getHandler() != null){
            return chainNode.getHandler();
        }
        return (IChainHandlerStrategy) beanContext.getBean(chainNode.getHandlerClass());
    }
}
